import store from '../index.js'
import fetchJsonp from 'fetch-jsonp'
import { Message } from 'element-ui'
import { m7Language } from '@/utils/m7Utils'
const URL = '/action'
const PUBLIC_URL = '/public'
const REPORT_URL = '/report'
const UBA_URL = '/uba/service'
const CLACK_URL = '/api/application'
const YY_URL = '/public2yy'
const AUTH_URL = '/auth/service'
const BILL_URL = '/action2bill'
const PUB_CC = '/public2cc'
const ROBOT_URL = '/action2robot'
const ignoreMessages = [
  'the_user_repeat',
  'unknow error!',
  'unknowerror!',
  'unknown_err',
  'unknown_error',
  '404 customer not found!',
  'action[wifi] is not support!',
  'get CommodityInfo error!',
  'The customer is in the state of being audited',
  'contains_forbidden_words',
  'webchat.webchat_not_finish', // 主动会话报错
  'remoteControl.code_bit_is_error',
  'code_not_exists',
  'data_exception',
  'claim failed',
  'webchat_cannot_withdraw_msg_before_two_min', // 超过2分钟消息不能撤销
  'query or taskList must has one',  //   智能质检 质检数据不能为空
  'expired_record_exists', // 通话批量导出录音任务
  'same_account_agent_phone_repeat' // 座席信息中的手机号重复

]

function openMessage (res, action) {
  if (res.success) {
    return null
  }
  let info = ''
  let errMsg = action ? action.errMsg : ''
  let resCode = res.code
  if (resCode === 'ECONNREFUSED' || resCode === 'connect ECONNREFUSED') { // 导出的时候，false,但是没有message。
    info = 'export_error'
  } else if (errMsg) {
    info = errMsg
  } else {
    info = res.Message ? res.Message : res.message
  }
  if (info && info !== '') {
    let reTag = /<(?:.|\s)*?>/g
    // if (info.substr(0, 8) === 'getCache') {
    //   // 获取缓存失败提示
    //   info = 'getCacheError'
    // }
    if (res.errorCode) {
      return
    }
    if (ignoreMessages.indexOf(info) > -1) { // 忽略判断。
      return
    } else {
      let language = m7Language(info, res.param).replace(reTag, '')
      Message({message: language, type: 'error', duration: 3000})
    }
  }
}
function commonThen (res, masking, action) {
  let response = res.json()
  response.then(function (data) {
    if (data.result === 403 && !window.sessionStorage.sessionId) {
      window.location.reload()
    }
    openMessage(data, action)
    if (action && action.action === 'common.getDicCache' && action.data && action.data.type === 'callLabel') {
      store.commit('ALL_KEY_LANELS', data.data || [])
    }
  })
  if (masking) {
    store.commit('MASKING', {show: false, type: 'common'})
  }
  // status code 2xx正常ruturn 其它走catch
  if (res.status.toString()[0] === '2') {
    return response
  } else {
    return Promise.reject(res)
  }
}
function commonCatch (res) {
  // status code 3xx不报错
  if (res.status && res.status.toString()[0] === '3') {
  } else {
    store.commit('SET_ERROR', 'message.default_tips')
  }
  return Promise.reject(res)
}
function fetchByPost (action, hiddenLoading, noSession, keepalive = false) {
  let sessionId = window.sessionStorage.getItem('sessionId')
  let loginToken = window.sessionStorage.getItem('loginToken')
  const langArr = ['zh_CN', 'zh_TW', 'en']
  let lang = window.localStorage.getItem('lang') || 'zh_CN'
  if (!langArr.includes(lang)) { // 做语言包校对。后端异常日志中有"lang":"zh_CNCN'等情况
    lang = 'zh_CN'
  }
  let data = {
    data: JSON.stringify(action.data),
    action: action.action,
    flag: 'kf',
    loginToken: '',
    sessionId: '',
    lang
  }
  if (store.getters.isEcommerce) {
    data.ecommerce = true
  }
  if (action.byBill) {
    data.page = action.page
    data.limit = action.limit
  }
  data.sessionId = action.action !== 'loginToAuthCenter' ? sessionId : ''
  data.loginToken = action.action !== 'loginToAuthCenter' ? loginToken : ''
  if (noSession) {
    data.sessionId = null
  }
  return window.fetch(action.url, {
    method: action.method || 'post',
    body: JSON.stringify(data),
    keepalive,
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, !hiddenLoading, action)
  }).catch((res) => {
    return commonCatch(res)
  })
}

function fetchByGet (action) {
  let sessionId = window.sessionStorage.getItem('sessionId')
  let loginToken = window.sessionStorage.getItem('loginToken')
  const langArr = ['zh_CN', 'zh_TW', 'en']
  let lang = window.localStorage.getItem('lang') || 'zh_CN'
  if (!langArr.includes(lang)) { // 做语言包校对。后端异常日志中有"lang":"zh_CNCN'等情况
    lang = 'zh_CN'
  }
  let data = {
    data: JSON.stringify(action.data),
    action: action.action,
    flag: 'kf',
    sessionId: '',
    lang
  }
  if (store.getters.isEcommerce) {
    data.ecommerce = true
  }
  console.log(action.action)
  data.sessionId = action.action !== 'loginToAuthCenter' ? sessionId : ''
  data.loginToken = action.action !== 'loginToAuthCenter' ? loginToken : ''
  let url = action.url + '?action=' + data.action + '&data= ' + data.data + '&sessionId=' + data.sessionId + '&loginToken=' + data.loginToken + '&lang=' + data.lang
  if (action.action === 'system.getUpNf') {
    url = action.url + '?action=' + data.action + '&data= ' + data.data + '&lang=' + data.lang
  }
  if (action.action === 'system.getCaptcha') {
    url = action.url + '?action=' + data.action + '&data= ' + data.data
  }
  return window.fetch(url, {
    method: action.method || 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, true, action)
  }).catch((res) => {
    return commonCatch(res)
  })
}

function fetchByJsonpGet (data) {
  let url = data.url + '?json=' + encodeURIComponent(JSON.stringify(data.jsonData))
  let timeout = 15000
  if (data.jsonData.Timeout !== undefined) {
    timeout = data.jsonData.Timeout
  }
  return new Promise((resolve, reject) => {
    fetchJsonp(url, {
      method: 'get',
      headers: {
        'Content-Type': 'application/json'
      },
      mode: 'cors',
      jsonpCallback: 'callbackName',
      timeout: timeout
    }).then(function (res) {
      let response = res.json()
      response.then(function (data) {
        if (data && data.result && data.result === 403 && !window.sessionStorage.sessionId) {
          window.location.reload()
        }
      })
      resolve(response)
      // store.commit('MASKING', {show: false, type: 'common'})
    }).catch(function (res) {
      return reject(res) // 异常外抛即可，不用里面做相关的逻辑处理 eg:ctiWaitEvent
    })
  })
}

function fetchByGetClack (data) {
  let url = CLACK_URL + '/' + data.data.id + '/' + data.data.name + '?authorization=' + data.data.authorization + '&sig=' + data.data.sig
  if (data.data.name === 'frames') {
    url += '&skip=' + data.data.skip + '&limit=' + data.data.limit
  }
  return window.fetch(url, {
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, false)
  }).catch((res) => {
    return commonCatch(res)
  })
}

function fetchByGetHetmap (data) {
  let url = CLACK_URL + '/' + data.data.userId + '/clickheatmap/urls?beginDate=' + data.data.beginDate + '&endDate=' + data.data.endDate + '&authorization=' + data.data.authorization + '&sig=' + data.data.sig
  if (data.data.url) {
    url = CLACK_URL + '/clickheatmap/day?beginDate=' + data.data.beginDate + '&endDate=' + data.data.endDate + '&url=' + data.data.url + '&authorization=' + data.data.authorization + '&sig=' + data.data.sig
  }
  return window.fetch(url, {
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, false)
  }).catch((res) => {
    return commonCatch(res)
  })
}

function fetchByGetPublicYy (data) {
  let url = YY_URL + '?action=' + data.action + '&data=' + JSON.stringify(data.data)
  return window.fetch(url, {
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, false)
  }).catch((res) => {
    return commonCatch(res)
  })
}
function GetXmlHttpObject () {
  let xmlHttp = null
  try {
    xmlHttp = new window.XMLHttpRequest()
  } catch (e) {
    try {
      xmlHttp = new window.ActiveXObject('Msxml2.XMLHTTP')
    } catch (e) {
      xmlHttp = new window.ActiveXObject('Microsoft.XMLHTTP')
    }
  }
  return xmlHttp
}

function fetchSycnByGet (action, sycn, method) {
  let xmlHttp = GetXmlHttpObject()
  let sessionId = window.sessionStorage.getItem('sessionId')
  let loginToken = window.sessionStorage.getItem('loginToken')
  const langArr = ['zh_CN', 'zh_TW', 'en']
  let lang = window.localStorage.getItem('lang') || 'zh_CN'
  if (!langArr.includes(lang)) { // 做语言包校对。后端异常日志中有"lang":"zh_CNCN'等情况
    lang = 'zh_CN'
  }
  let data = {
    data: JSON.stringify(action.data),
    action: action.action,
    flag: 'kf',
    sessionId: '',
    lang: lang
  }
  if (store.getters.isEcommerce) {
    data.ecommerce = true
  }
  data.sessionId = action.action !== 'loginToAuthCenter' ? sessionId : ''
  data.loginToken = action.action !== 'loginToAuthCenter' ? loginToken : ''
  let url = action.url
  if (method !== 'POST') {
    url += ('?action=' + data.action + '&data= ' + data.data + '&sessionId=' + data.sessionId + '&loginToken=' + data.loginToken + '&lang=' + data.lang)
  }
  if (xmlHttp == null) {
    return
  }
  return new Promise((resolve, reject) => {
    xmlHttp.onreadystatechange = function () {
      if (xmlHttp.readyState === 4) {
        let response = JSON.parse(xmlHttp.responseText)
        resolve(response)
      }
    }
    xmlHttp.open(method || 'GET', url, sycn)
    let send = null
    if (method === 'POST') {
      send = JSON.stringify(data)
      xmlHttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
    }
    xmlHttp.send(send)
  })
}
function fetchByRobot (action, hiddenLoading, noSession) {
  let sessionId = window.sessionStorage.getItem('sessionId')
  let loginToken = window.sessionStorage.getItem('loginToken')
  const langArr = ['zh_CN', 'zh_TW', 'en']
  let lang = window.localStorage.getItem('lang') || 'zh_CN'
  if (!langArr.includes(lang)) { // 做语言包校对。后端异常日志中有"lang":"zh_CNCN'等情况
    lang = 'zh_CN'
  }
  let data = {
    data: JSON.stringify(action.data) || {},
    flag: 'kf',
    loginToken: '',
    sessionId: '',
    lang
  }
  if (store.getters.isEcommerce) {
    data.ecommerce = true
  }
  if (action.byBill) {
    data.page = action.page
    data.limit = action.limit
  }
  data.sessionId = action.action !== 'loginToAuthCenter' ? sessionId : ''
  data.loginToken = action.action !== 'loginToAuthCenter' ? loginToken : ''
  if (noSession) {
    data.sessionId = null
  }
  return window.fetch(action.url, {
    method: action.method || 'post',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    return commonThen(res, !hiddenLoading, action)
  }).catch((res) => {
    return commonCatch(res)
  })
}
export default {
  fetch (data, method, hiddenLoading, noSession, keepalive) {
    let action = data
    action.url = URL
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return method === 'post' ? fetchByPost(action, hiddenLoading, noSession, keepalive) : fetchByGet(action, hiddenLoading)
  },
  fetchByPublic (data, method, hiddenLoading) {
    let action = data
    action.url = PUBLIC_URL
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return method === 'post' ? fetchByPost(action, hiddenLoading) : fetchByGet(action, hiddenLoading)
  },
  fetchByPublicSycn (data) {
    let action = data
    action.url = PUBLIC_URL
    return fetchSycnByGet(action, false)
  },
  fetchByActionSycn (data) {
    let action = data
    action.url = URL
    return fetchSycnByGet(action, false, 'POST')
  },
  fetchByReport (data, method, hiddenLoading) {
    let action = data
    action.url = REPORT_URL
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return method === 'post' ? fetchByPost(action, hiddenLoading) : fetchByGet(action, hiddenLoading)
  },
  fetchByUba (data, method) {
    let action = data
    action.url = UBA_URL
    // store.commit('MASKING', {show: true, type: 'common'})
    return method === 'post' ? fetchByPost(action) : fetchByGet(action)
  },
  fetchByAuth (data, method) {
    let action = data
    action.url = AUTH_URL
    store.commit('MASKING', {show: true, type: 'common'})
    return method === 'post' ? fetchByPost(action) : fetchByGet(action)
  },
  fetchByJsonp (data, method) {
    // store.commit('MASKING', {show: false, type: 'common'})
    return fetchByJsonpGet(data)
  },
  fetchByClack (data, method) {
    // store.commit('MASKING', {show: false, type: 'common'})
    return fetchByGetClack(data)
  },
  fetchByBill (data, method, hiddenLoading) {
    let action = data
    action.url = BILL_URL
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return method === 'post' ? fetchByPost(action) : fetchByGet(action)
  },
  fentchByPub2CC (data, method, hiddenLoading) {
    let action = data
    action.url = PUB_CC
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return method === 'post' ? fetchByPost(action) : fetchByGet(action)
  },
  fentchByRobot (data, method, hiddenLoading) {
    let action = data
    action.url = ROBOT_URL + '/' + data.action
    if (!hiddenLoading) {
      store.commit('MASKING', {show: true, type: 'common'})
    }
    return fetchByRobot(action)
  },
  fetchByHeatmap (data, method) {
    // store.commit('MASKING', {show: false, type: 'common'})
    return fetchByGetHetmap(data)
  },
  fetchByPublicYy (data, method) {
    // store.commit('MASKING', {show: false, type: 'common'})
    return fetchByGetPublicYy(data)
  }
}
